
import { getArticleDetail, addComment } from "@/api/api";
import methods from "./articleFavorites";
import commentLists from "./commentList";
import replyComponent from "./replyComponent.vue";
import { mapState } from "vuex";
// 美化布局
import "@/common/github-markdown.css";

import QRCode from 'qrcode'
import html2canvas from 'html2canvas'

export default {
  name: "Article",
  data() {
    return {
      remarks: false,
      content: "",

      title: "",
      article_id: "",
      article: {},
      comment_type: 0,
      contentHigh: 0, //分割线以上高度
      contentPlaceholder: "请留下你的精彩评论吧",

      reply_comment_id: "", //  回复的评论的 ID
      active_reply_index: 0,
      replyRemarks: false,

      showShare: false,

      options: [
        [
          { name: '微信', icon: 'wechat' },
          { name: '微博', icon: 'weibo' },
          { name: 'QQ', icon: 'qq' },
          { name: '复制链接', icon: 'link' },
        ],
        [
          { name: '二维码', icon: 'qrcode' },
          { name: '分享海报', icon: 'poster' },
        ],
      ],

      qrcodePopup: false,
      qrcodeurl: '',
    };
  },
  components: {
    [replyComponent.name]: replyComponent,
  },
  mixins: [commentLists],
  computed: {
    ...mapState(["uid", "userInfo"]),
  },
  created() {
    let { id, title } = this.$route.query;
    this.article_id = id;
    this.title = title;
    this.getArticleDetail();
  },
  methods: {
    // 复制
    copy(params) {
      let input = document.createElement('input')
      input.value = params

      // 隐藏

      // input.type = 'hidden'
      document.body.appendChild(input)
      input.select()
      // 复制  定值
      document.execCommand('copy')
      document.body.removeChild(input)
    },
    // 分享海报
    crossAvatar(url) {
      return new Promise(function (resolve) {
        fetch(url).then(function (response) {
          response.blob().then((res) => {
            let fileReader = new FileReader();

            fileReader.readAsDataURL(res);

            fileReader.onload = function (e) {
              resolve(e.target.result);
            };
          });
        });
      });
    },


    // 微博
    shareTSina() {
      let img = this.article.imageSrc[0];
      let title = this.article.title;
      console.log(img)
      let url = window.location.href;

      window.open("http://service.weibo.com/share/share.php?pic=" + encodeURIComponent(img) + "&title=" +
        title + "&url=" + url);
    },

    // QQ
    shareQQ() {

      let img = this.article.imageSrc[0];
      let title = this.article.title;

      console.log(img)

      let url = window.location.href;
      window.open("http://connect.qq.com/widget/shareqq/index.html?pic=" + encodeURIComponent(img) + "&title=" +
        title + "&url=" + url);
    },

    //   微信/二维码
    qrcode() {
      let url = window.location.href;
      QRCode.toDataURL(url)
        .then(url => {
          console.log(url)

          this.qrcodeurl = url;
          this.qrcodePopup = true

        })
        .catch(err => {
          console.error(err)     //////
        })

    },


    // 分享发送
    async onSelect({ name }) {
      // console.log(name)

      switch (name) {


        case '微博':
          this.shareTSina()
          break;

        case 'QQ':
          this.shareQQ()
          break;


        case '复制链接':
          console.log(window.location.href)
          this.$toast('复制成功')
          this.copy(window.location.href)
          break;

        case '微信':
        case '二维码':
          this.qrcode();
          break;

        // 分享海报

        case '分享海报':
          let contentHigh = this.$refs.contentHigh
          if (contentHigh) {

            // 利用base64下载解决跨域问题
            let base64Avatar = await this.crossAvatar(this.article.avatar);
            this.article.avatar = base64Avatar;

            setTimeout(v=>{
              html2canvas(contentHigh, {
                // 获取图片头像
                allowTaint: true
              }).then(canvas => {
                console.log(canvas)
  
                // 图片
                let cxt = canvas.getContext('2d')
                let img = new Image()
                img.src = require('@/views/article/cxy.png')
                
                img.setAttribute("crossOrigin", "anonymous");
  
                img.onload = function () {
  
                  cxt.drawImage(img, 20, 20)
  
                  // 转化成图片
                  let res = canvas.toDataURL()
                  console.log(res)
  
                  // 看一下是否生效   不需要写
                  // contentHigh.appendChild(canvas)
                }
              }).catch(err => {
  
              })
            },500)
            
          }

      }

      this.showShare = false;
    },


    ...methods,

    // 打开评论框
    openRemarks() {
      if (!this.checkLogin()) return;
      this.contentPlaceholder = "请留下你的精彩评论吧";
      this.comment_type = 0;
      this.remarks = true;

      // 聚焦
      this.$nextTick(function () {
        // console.log(this.$refs.content);
        this.$refs.content.focus();
      });
    },


    // 打开评论回复框
    openReply(item, index, is_child) {

      // 是否登录
      if (!this.checkLogin()) return;

      let {
        reply_num,
        info: { nickname },
        _id: reply_comment_id,
      } = item;
      this.active_reply_index = index;

      if (reply_num == 0 || is_child) {

        //  如果没人回复
        this.remarks = true;
        this.comment_type = 1;
        this.contentPlaceholder = "回复:" + nickname;
        this.reply_comment_id = reply_comment_id;

        // 聚焦
        this.$nextTick(function () {
          // console.log(this.$refs.content);
          this.$refs.content.focus();
        });
      } else {
        this.replyRemarks = true;
      }
    },

    // 文章详情
    getArticleDetail() {
      let { article_id, uid: user_id } = this;

      getArticleDetail({
        article_id,
        user_id,
      }).then((res) => {
        console.log(res);

        if (res.code == 0) {
          this.article = res.data;

          // 下一次dom更新成功之后

          this.$nextTick(function () {
            // 高度计算

            // console.log(this.$refs.contentHigh.offsetHeight);
            this.contentHigh = this.$refs.contentHigh.offsetHeight;
          });
        } else {
          this.$toast(res.msg);
        }
      });
    },

    addComment() {
      let { uid: user_id, article_id, content, comment_type, reply_comment_id } = this;

      content = content.trim();

      if (content.length == 0) {
        this.$toast("请输入评论内容");
        return;
      }

      //发布评论
      addComment({
        user_id,
        article_id,
        content,
        comment_type,
        reply_comment_id,
      }).then((res) => {

        this.$toast(res.msg);

        if (res.code == 0) {
          this.remarks = false;
          // 角标加一
          this.article.comment++;
          //  清空原数据      新数据加载到页面
          this.content = "";
          //严谨但浪费 用户体验比较差
          // this.skip = 0;
          // this.comment_finished = false;
          // this.commentList = [];
          // this.getCommentList();

          if (comment_type == 0) {
            // 组装数据
            let { avatar, nickname, username } = this.userInfo;

            let commentData = {
              article_id,
              comment_type: 0,
              content,
              create_time: new Date().getTime(),
              info: { avatar, nickname, username },
              is_like: false,
              like_count: 0,
              reply_comment_id: "",
              reply_num: 0,
              user_id,
              _id: res.data.id,
            };

            this.skip++;
            this.commentList.unshift(commentData);
            // 计算高度

            this.$refs.contentHigh.scrollTo(0, this.contentHigh);
          } else if (comment_type == 1) {

            // 如果二级评论回复组件存在


            if (this.replyRemarks) {
              this.$Bus.$emit('listRefresh')

            } else {

              this.commentList[this.active_reply_index].reply_num++;
              let index = this.active_reply_index
              let item = this.commentList[index]
              this.openReply(item, index)
            }
          }
        }
      });
    },
  },
}